package com.qire.manhua.model.viewModel.impl;

import android.view.View;
import android.widget.BaseAdapter;

import com.qire.antsrouter.AntsRouter;
import com.qire.antsrouter.lifecycleHandler.ActivityManageHandler;
import com.qire.common.constant.Navigation;
import com.qire.common.support.AbsBringDialogViewModel;
import com.qire.common.support.DialogFastBuildUtil;
import com.qire.common.support.base.IViewModel;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.activity.TaskCenterActivity;
import com.qire.manhua.controller.TaskCenterController;
import com.qire.manhua.dal.service.TaskCenterService;
import com.qire.manhua.databinding.LayoutTaskItemBinding;
import com.qire.manhua.dialog.ReceiveTaskRewardsDialog;
import com.qire.manhua.model.entity.TaskEntity;
import com.qire.common.model.enumeration.RewardType;

import java.util.ArrayList;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;

public class TaskCenterViewModel extends AbsBringDialogViewModel implements IViewModel {

    private TaskCenterService taskCenterService = new TaskCenterService(this);

    /** 日常任务列表 */
    private final ArrayList<TaskItemViewModel> dailyTaskList    = new ArrayList<>();
    /** 新手任务列表(目标任务) */
    private final ArrayList<TaskItemViewModel> newcomerTaskList = new ArrayList<>();//aimsTask

    private SummerBindAdapter dailyTaskAdapter = new SummerBindAdapter(dailyTaskList);
    private SummerBindAdapter newcomerTaskAdapter = new SummerBindAdapter(newcomerTaskList);

    @Override
    public int getVariableId() {
        return BR.taskCenterViewModel;
    }


    //region    #附加管理 begin
    /**
     * 附加属性绑定
     * @param controller 事件控制器
     */
    public void onAddition(TaskCenterController controller) {
        dailyTaskAdapter.setEventProcess(controller);
        newcomerTaskAdapter.setEventProcess(controller);
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，
     * 页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        taskCenterService = null;
        dailyTaskAdapter.setEventProcess(null);
        newcomerTaskAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    //region    #业务 begin

    public void loadPageData() {
        taskCenterService.loadTaskListData();
    }
    public void loadSignInData() {
        taskCenterService.loadSignInInfo();
    }

    public void clearDailyTaskList() {
        dailyTaskList.clear();
    }
    public void addDailyTaskItem(TaskEntity taskEntity) {
        dailyTaskList.add(new TaskItemViewModel(taskEntity));
    }
    public void clearNewcomerTaskList() {
        newcomerTaskList.clear();
    }
    public void addNewcomerTaskItem(TaskEntity taskEntity) {
        newcomerTaskList.add(new TaskItemViewModel(taskEntity));
    }
    public void refreshAdapter() {
        dailyTaskAdapter.notifyDataSetChanged();
        newcomerTaskAdapter.notifyDataSetChanged();
    }

    public void changeSignInPanelData(String signInTips, boolean isNewcomer, String[] nodeTests, int daysNumber) {
        set("signInTips", signInTips);
        set("newSignInTipsVisible", isNewcomer ? View.VISIBLE : View.GONE);
        set("nodeTexts", nodeTests);
        set("daysNumber", daysNumber);
    }

    public void bindWeChat() {
        taskCenterService.bindWeChat();
    }

    //endregion #业务 end

    // region #UI操作

    public void refreshUI() {
        refreshTaskPanel();
    }
    public void refreshTaskPanel() {

    }

    public void changeNavBarBgAlpha(int alpha) {
        set("navBarBgAlpha", alpha);
    }

    /**
     * 显示领取任务奖励弹窗
     * @param titleText     任务奖励标题
     * @param msgText       任务奖励信息描述
     * @param rewardType    任务奖励类型
     */
    public void showReceiveTaskRewardsDialog(String titleText, String msgText, RewardType rewardType, boolean isDouble, View.OnClickListener confirmBtnListener) {
        TaskCenterActivity taskCenterActivity = (TaskCenterActivity) ActivityManageHandler.HANDLER.findActivityBy(TaskCenterActivity.class);
        ReceiveTaskRewardsDialog.Builder.builder(taskCenterActivity, rewardType)
                .setTitleText(titleText)
                .setTipsText(msgText)
                .setDouble(isDouble)
                .setConfirmBtnListener(confirmBtnListener)
                .show();
    }

    public void showBindWeChatResultDialog() {
        final DialogFastBuildUtil.Builder builder = DialogFastBuildUtil.builder(R.layout.dialog_common_prompt_light_r);
        builder.setTextView(R.id.dialog_title, "绑定成功")
                .setTextView(R.id.dialog_content, "赶快关注“奇热漫画”公众号领取奖励吧")
                .setTextView(R.id.dialog_button_dark, "下次再说", view -> {
                    builder.dismiss();
                    view.setOnClickListener(null);
                })
                .setTextView(R.id.dialog_button_light, "去关注", view -> AntsRouter.ROUTER.buildCard(Navigation.Page.SubscribeWeChatPage).navigation())
                .show();
    }

    // endregion #UI操作 end

    // region #UI属性绑定

    public MutableLiveData<Integer> getNavBarBgAlpha() {
        return get("navBarBgAlpha");
    }

    public MutableLiveData<CharSequence> getSignInTips() {
        return get("signInTips");
    }

    public MutableLiveData<Integer> getNewSignInTipsVisible() {
        return get("newSignInTipsVisible");
    }

    public MutableLiveData<Integer> getDaysNumber() {
        return get("daysNumber");
    }

    public MutableLiveData<String[]> getNodeTexts() {
        return get("nodeTexts");
    }

    public BaseAdapter getDailyTaskAdapter(){
        return dailyTaskAdapter;
    }

    public BaseAdapter getNewcomerTaskAdapter(){
        return newcomerTaskAdapter;
    }
    // endregion


    @AdapterEntityBind(viewRid = R.layout.layout_task_item)
    public class TaskItemViewModel extends BaseObservable implements AutoVariable<LayoutTaskItemBinding> {

        public final TaskEntity taskEntity;

        public TaskItemViewModel(TaskEntity taskEntity){
            this.taskEntity = taskEntity;
        }

        @Override
        public void bindVariable(LayoutTaskItemBinding viewBind) {
            viewBind.setTaskItemViewModel(this);
        }

        /**
         * @return 任务实体的ID
         */
        public int taskID(){
            return taskEntity.id;
        }

        /**
         * 领取奖励
         */
        public void receiveReward() {
            taskCenterService.receiveRewardBy(this);
        }

        /**
         * 显示奖励结果：弹出任务奖励领取弹窗，并修改任务状态
         */
        public void showReward() {
            String msgText = "+" + taskEntity.getRewardInfo();
            showReceiveTaskRewardsDialog("领取成功", msgText,taskEntity.rewardType, false, null);
            taskEntity.receiveReward();
            notifyChange();
        }

        /**
         * 是否可领取
         * @return 可领取返回true,否则false;
         */
        public boolean canReceive(){
            return taskEntity.canReceive();
        }

        /**
         * 是否未完成
         * @return 未完成返回true,否则false;
         */
        public boolean unfinished(){
            return taskEntity.unfinished();
        }


        @Bindable
        public CharSequence getTaskName(){
            return taskEntity.taskName;
        }

        @Bindable
        public CharSequence getRewardInfo(){
            return "奖励" + taskEntity.getRewardInfo();
        }

        @Bindable
        public CharSequence getRewardBtnText(){
            if(taskEntity.unfinished()&&taskEntity.id==109)
                return "立即绑定";
            return taskEntity.state.text;
        }

        @Bindable
        public String getRewardBtnTextColor(){
            return taskEntity.state.textColor;
        }

        @Bindable
        public int getRewardBtnBgRid(){
            return taskEntity.state.textBgRid;
        }

    }

}
